﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using GT.Algorithms;
using System.IO;
using hieunv.Logs;
using System.Collections.Generic;
using System.Threading;
using System.Text.RegularExpressions;
using GT.Ultilities;
namespace GT.App
{
	public partial class App : Form
	{
		public const string PROGRAM_NAME = "KEA v1.0 - ";
		public const int MAX_KEYWORDS = 15;
		public const string CORPUS_PATH = "Corpus";
		private KEA _kea;

		public App()
		{
			InitializeComponent();
		}
		#region Events
		private void _mniOpen_Click(object sender, EventArgs e)
		{
			Open();
		}
		private void _mniExit_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}
		private void _miPreprocess_Click(object sender, EventArgs e)
		{
			Preprocess();
		}
		private void _miConstructGST_Click(object sender, EventArgs e)
		{
			Construct();
		}
		private void _miComputeIDF_Click(object sender, EventArgs e)
		{
			ComputeIDF();
		}
		private void _mniExtract_Click(object sender, EventArgs e)
		{
			Extract();
		}
		//private void _rbtnTFIDF_CheckedChanged(object sender, EventArgs e)
		//{
		//    Extract();
		//}
		//private void _rbtnWFIDF_CheckedChanged(object sender, EventArgs e)
		//{
		//    Extract();
		//}
		private void _trvGST_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			try
			{
				AddNodes(e.Node);
				foreach (TreeNode x in e.Node.Nodes)
				{
					AddNodes(x);
				}
			}
			catch (Exception exc)
			{
				MessageBox.Show(exc.Message);
			}
		}
		#endregion
		#region Methods

		/// <summary>
		/// Đọc văn bản.
		/// </summary>
		/// <param name="path">Đường dẫn đến tệp tin.</param>
		/// <returns>Nội dung văn bản.</returns>        
		public static string ToText(string path)
		{
			string ext = Path.GetExtension(path);
			switch (ext)
			{
				case ".txt": return File.ReadAllText(path);
				case ".pdf": return PDF.Text(path);
				case ".docx": return Docx.Text(path);
				default: return null;
			}
		}
		/// <summary>
		/// Chọn tệp tin.
		/// </summary>
		private void Open()
		{
			if (this._odg.ShowDialog() == DialogResult.OK)
			{
				this.Text = PROGRAM_NAME + this._odg.FileName;
				this._rbxText.Text = ToText(this._odg.FileName);
			}
		}
		/// <summary>
		/// Tiền xử lý.
		/// </summary>
		private void Preprocess()
		{
			this._rbxPreprocessText.Text = GST.Preprocess(this._rbxText.Text);
			this._tc.SelectedTab = this._tpPreprocess;
			this._kea = new KEA(this._rbxPreprocessText.Text);

			this._kea.EndConstructGST += new EventHandler((s, a) =>
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() =>
					{
						this._trvGST.Nodes.Clear();
						TreeNode x = new TreeNode("/");
						x.Tag = this._kea.GST.Root;
						this._trvGST.Nodes.Add(x);
						AddNodes(x);
						this._tc.SelectedTab = this._tpViewGST;
					}));
				}
			});
			this._kea.EndComputeIDF += new EventHandler((s, a) =>
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() =>
					{
						this._lvWords.Items.Clear();
						List<Node> nodes = this._kea.Nodes;
						foreach (Node x in nodes)
						{
							ListViewItem xx = new ListViewItem(new string[] { "", x.Text, x.TF.ToString(), x.IDF.ToString() });
							this._lvWords.Items.Add(xx);
						}
						this._tc.SelectedTab = this._tpExtract;
					}));
				}
			});
			this._kea.EndExtract += new EventHandler((s, a) =>
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() =>
					{
						this._lvWords.Items.Clear();
						List<Node> nodes = this._kea.Nodes;
						
						//foreach (Node x in nodes)
						//{
						//    this._lvWords.Items.Add(new ListViewItem(new string[] { "", x.Text, x.TF.ToString(), x.IDF.ToString(), x.Weight.ToString() }));
						//}
						for (int i = 0; i < (int)this._nudKeywords.Value; i++)
						{
							Node x = nodes[i];
							this._lvWords.Items.Add(new ListViewItem(new string[] { "", x.Text, x.TF.ToString(), x.IDF.ToString(), x.Weight.ToString() }));
						}
					}));
				}
			});
			this._kea.Report += new EventHandler<ReportEventArgs>((s, a) =>
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() =>
					{
						this._tsslAction.Text = a.Action;
						this._tspbProcessing.Value = a.Percentage;
					}));
				}
			});
		}
		private void Construct()
		{
			try
			{
				this._kea.ConstructGST();
			}
			catch (Exception exc)
			{
				MessageBox.Show(exc.Message);
			}
		}
		private void AddNodes(TreeNode x)
		{
			if (x.Nodes.Count > 0) return;
			Node n = x.Tag as Node;
			if (n.Node0 != null)
			{
				TreeNode x1 = new TreeNode(n.Node0.NodeText);
				x1.Tag = n.Node0;
				x.Nodes.Add(x1);
				Node next = n.Node0.Next;
				while (next != null)
				{
					TreeNode x2 = new TreeNode(next.NodeText);
					x2.Tag = next;
					x.Nodes.Add(x2);
					next = next.Next;
				}
			}
		}
		private void ComputeIDF()
		{
			this._kea.Paths.AddRange(Directory.GetFiles(Application.StartupPath + "\\" + CORPUS_PATH));
			this._kea.ComputeIDF();
		}
		private void Extract()
		{
			using (StreamWriter sw = File.AppendText("Logs.txt"))
			{
				sw.WriteLine(this._odg.FileName);
				foreach (Node x in this._kea.Nodes)
				{
					sw.WriteLine(string.Format("{0}({1}, {2:0.000}, {3:0.000})", x.Text, x.TF, x.IDF, x.Weight));
				}
			}
		}
		#endregion

		private void _rbTFIDF_Click(object sender, EventArgs e)
		{
			if (this._rbTFIDF.Checked)
			{
				if (this._cbUseInnovativeMethods.Checked)
				{
					this._kea.Extract(Weight.TFIDF);
				}
				else this._kea.Extract(Weight.TFIDF, false);
			}
		}

		private void _rbWFIDF_Click(object sender, EventArgs e)
		{
			if (this._rbWFIDF.Checked)
			{
				if (this._cbUseInnovativeMethods.Checked)
				{
					this._kea.Extract(Weight.WFIDF);
				}
				else this._kea.Extract(Weight.WFIDF, false);
			}
		}

		private void _rbNTFIDF_Click(object sender, EventArgs e)
		{
			if (this._rbNTFIDF.Checked)
			{
				if (this._cbUseInnovativeMethods.Checked)
				{
					this._kea.Extract(Weight.NTFIDF);
				}
				else this._kea.Extract(Weight.NTFIDF, false);
			}
		}

		private void _miAddDocument_Click(object sender, EventArgs e)
		{
			Documents.Instance.Show();
		}

		private void _cbUseInnovativeMethods_Click(object sender, EventArgs e)
		{
			if (this._cbUseInnovativeMethods.Checked)
			{
				if (this._rbTFIDF.Checked) this._kea.Extract(Weight.TFIDF);
				else if (this._rbWFIDF.Checked) this._kea.Extract(Weight.WFIDF);
				else if (this._rbNTFIDF.Checked) this._kea.Extract(Weight.NTFIDF);
			}
			else
			{
				if (this._rbTFIDF.Checked) this._kea.Extract(Weight.TFIDF, false);
				else if (this._rbWFIDF.Checked) this._kea.Extract(Weight.WFIDF, false);
				else if (this._rbNTFIDF.Checked) this._kea.Extract(Weight.NTFIDF, false);
			}
		}
	}
}
